/**
 *
 *  Copyright (c) 2011, AstroDAbis
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification,
 *  are permitted provided that the following conditions are met:
 *
 *      * Redistributions of source code must retain the above copyright notice,
 *        this list of conditions and the following disclaimer.
 *      * Redistributions in binary form must reproduce the above copyright notice,
 *        this list of conditions and the following disclaimer in the documentation
 *        and/or other materials provided with the distribution.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 *  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *  OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
package org.jiscinvolve.astrodabis.mallow.control.login;

import java.util.List;
import java.util.Date;

import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import javax.validation.Valid;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.context.request.WebRequest;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.beans.propertyeditors.PatternEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;


import org.springframework.ui.Model;
import org.springframework.validation.FieldError;
import org.springframework.validation.BindingResult;

/**
 * Login controller
 * http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html
 * http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/web/servlet/mvc/Controller.html
 *
 */
@Controller
@RequestMapping("/login")
public class TestController
    {

// Notification of the servlet context.
// http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/web/context/ServletContextAware.html
// extends org.springframework.web.context.ServletContextAware
    /**
     * Our debug logger.
     * 
     */
    private static Log log = LogFactory.getLog(TestController.class);

    /**
     * Initialise our data binder.
     * @see http://static.springsource.org/spring/docs/3.0.x/reference/validation.html#validation-mvc-configuring
     * Replaced by bean annotations.
     * @see http://static.springsource.org/spring/docs/3.0.x/reference/validation.html#validation-mvc-jsr303
     * 
    @InitBinder
    public void init(final WebDataBinder binder)
        {
        log.debug("LoginController.init(....)");
        //
        // Set the list of fields the data binder should ignore .
        binder.setDisallowedFields(
            new String[]
                {
                "id"
                }
            );
        //
        // Set the list of required fields.
        binder.setRequiredFields(
            new String[]
                {
                "name",
                "age",
                }
            );
        //
        // Add our PropertyEditors.
        binder.registerCustomEditor(
            Date.class,
            "date",
            new CustomDateEditor(
                new SimpleDateFormat(
                    "dd-MM-yyyy"
                    ),
                false
                )
            );
        binder.registerCustomEditor(
            Integer.class,
            "age",
            new CustomNumberEditor(
                Integer.class,
                new DecimalFormat(
                    "#0"
                    ),
                false                
                )
            );
        binder.registerCustomEditor(
            String.class,
            "name",
            new StringTrimmerEditor(
                false                
                )
            );
        }
     */

    /**
     * Get request.
     * 
     */
	@RequestMapping(method=RequestMethod.GET)
	public void get(WebRequest request, HttpSession session, Model model)
	    {
        log.debug("LoginController.get(....)");
        LoginForm form = (LoginForm) request.getAttribute("form", WebRequest.SCOPE_REQUEST);
        if (form != null)
            {
            log.debug("Got form");
            log.debug("  Name [" + form.getName() + "]");
            model.addAttribute(form);
            }
        else {
            log.debug("No form");
            model.addAttribute(new LoginForm());
            }
        }

    /**
     * Post request.
     * 
     */
	@RequestMapping(method=RequestMethod.POST)
	public String submit(@Valid LoginForm form, BindingResult result, WebRequest request, HttpSession session, Model model) 
	    {
        log.debug("LoginController.submit(....)");
		if (result.hasErrors())
		    {
            log.debug("Form has errors");
            log.debug("  Name [" + form.getName() + "]");
            log.debug("  Age  [" + form.getAge() + "]");
            log.debug("  Date [" + form.getDate() + "]");

            List<FieldError> errors = result.getFieldErrors();
            for(FieldError error : errors)
                {
                log.debug("  Error [" + error.getField() + "][" + error.getDefaultMessage() + "]");
                }

			return null;
		    }
        else {
            log.debug("Form is valid");
            log.debug("  Name [" + form.getName() + "]");
            log.debug("  Age  [" + form.getAge() + "]");
            log.debug("  Date [" + form.getDate() + "]");

			return null;
            }

		// simply store form bean in the session for demo purposes, typically you would save form bean values to a db
/*
		session.setAttribute("form", form);
		String message = "Form submitted successfully.  Bound " + form;
		//
		// success response handling
		if (AjaxUtils.isAjaxRequest(webRequest))
		    {
			// prepare model for rendering success message in this request
			model.addAttribute("message", new Message(MessageType.success, message));
			model.addAttribute("ajaxRequest", true);
			return null;
		    }
	    else {
			// store a success message for rendering on the next request after redirect
			FlashMap.setSuccessMessage(message);
			// redirect back to the form to render the success message along with newly bound values
			return "redirect:/form";			
		    }
 */
	    }
    }

